import 'package:demo/empUtils/EMPButton.dart';
import 'package:demo/empUtils/EMPColorUtils.dart';
import 'package:demo/empUtils/EMPLayoutUtils.dart';
import 'package:demo/empUtils/EMPTextFieldItem.dart';
import 'package:demo/testList.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';

import 'EmpMineSetVC.dart';
import 'empUtils/EMPImageUtils.dart';
import 'testLayout.dart';
import 'package:demo/EMPWebview.dart';

import 'package:sqflite/sqflite.dart';

import 'inapp_webview/inapp_webview_page.dart';

import 'inapp_webview/webview_page.dart';

// com.jlfi.evoportal
import 'sqltest.dart';

import 'package:url_launcher/url_launcher.dart';

import 'testfont.dart';
import 'package:provider/provider.dart';
import 'empUtils/FontSizeModel.dart';
import 'package:demo/empUtils/EMPPreferencesHelper.dart';
import 'empUtils/push/XMqttClientSecure.dart';


import 'EMPTestCustomCellTwoVC.dart';
import 'EMPTestCustomCellVC.dart';
import 'EMPTestCustomGroupCellVC.dart';
import 'textbook.dart';
import 'testAPP.dart';

// void main() => runApp(
//     MultiProvider(
//       providers: [
//         ChangeNotifierProvider(create: (ctx)=>MyCounter()),
//         ChangeNotifierProvider(create: (ctx)=>MySubtract()),
//       ],
//       child: MyAppFontTest(),
//     )
// );

// void main() {
//   runApp(MyAppfont());
// }

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  // String phoneNo = TextUtil.formatSpace4("15845678910"); // 1584 5678 910

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'evoPortal',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'evoPortalTest'),
    );
  }
}



class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
  // State<MyHomePage> createState() => _MyHomePageStateMqtt();
}

class _MyHomePageStateMqtt extends State<MyHomePage> {
  int _counter = 0;
  List<String> get topics => ["msg/28641","public"];
  void _incrementCounter() {
    setState(() {
      _counter++;
      if (_counter == 1) {
        XMqttClientSecure.instance.connect("6727b2a71e6d4558890d373be3843419")
            .then((value) => {
          XMqttClientSecure.instance.topicSubscribe(topics)
        });
      }
    });
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}



class _MyHomePageState extends State<MyHomePage> {


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          title: Text(widget.title),
        ),
        body: Center(
          child: buildColumn(),
        ));
  }

  // final filedddd = EMPTextFieldItem(title: '输入框',hintText: '占位文字');

  Widget buildColumn() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        const Text('测试测试'),
        Image(
          image: EMPImageUtils.getAssetImage('other/setting'),
          width: 15,
        ),
        Text(
          '哈哈哈aaaa',
          style: Theme.of(context).textTheme.headlineMedium,
        ),
        // EMPLayout.empty,
        buildButton(),
        EMPLayout.vGap15,
        buildRow(),
        EMPLayout.vGap15,
        // filedddd
        const EMPTextFieldItem(
          title: '输入框',
          hintText: '占位文字',
        ),
      ],
    );
  }

  Widget buildButton() {
    return EMPButton(
      text: 'aaa',
      minHeight: 44,
      minWidth: 200,
      onPressed: () {
        print('Button Clicked!');

        insertTestData();
        // displayTestData();
        // deleteAllData();

        Navigator.push(
          context,

            // MaterialPageRoute(builder: (context) => AnotherPage()),

        // MaterialPageRoute(builder: (context) => const testListPage()),
          //   MaterialPageRoute(builder: (context) => const ExamPage()),
          //   MaterialPageRoute(builder: (context) => const testLayout()),
          //   MaterialPageRoute(builder: (context) =>  EMPWebView()),

            MaterialPageRoute(builder: (context) =>  EMPTestCustomCellVC(title: '测试自定义cell',)),
            // MaterialPageRoute(builder: (context) =>  EMPTestCustomCellTwoVC(title: '测试自定义cell',)),
          // MaterialPageRoute(builder: (context) =>  EMPTestCustomGroupCellVC(title: '测试自定义cell',)),

            // MaterialPageRoute(builder: (context) =>  testAPP()),



            // MaterialPageRoute(builder: (context) =>  HomeView()),

            // MaterialPageRoute(builder: (context) =>  WebViewPage(baseUrl: 'https://www.baidu.com',)),

          // MaterialPageRoute(builder: (context) =>  InAppWebViewPage(baseUrl: 'https://www.baidu.com',)),


          // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            //   return const WebViewPage(baseUrl: '');
            // }));

              // MaterialPageRoute(builder: (context) => ExamplHtmlUrlPage()),

            // _launchURL()

        );
      },
    );
  }

  _launchURL() async {
    const url = 'https://flutterchina.club/';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw '无法打开网页 $url';
    }
  }

  Widget buildRow() {
    return Container(
      color: Colors.blue,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('测试测试'),
          Text('yuan'),
          EMPLayout.hGap10,
          buildRowMore(),
        ],
      ),
    );
  }

  Widget buildRowMore() {
    return Container(
      color: Colors.orange,
      padding: EdgeInsets.all(5),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: const <Widget>[
          Padding(
            padding: EdgeInsets.all(1),
            child: Text(
              '哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈',
              style: TextStyle(color: EMPColor.red, backgroundColor: Colors.purple, fontSize: 20),
              softWrap: true,
            ),
          )
        ],
      ),
    );
  }



  // Future<void> insertTestData() async {
  //   List<Map<String, dynamic>> batchData = [];
  //   for (int i = 0; i < 1000; i++) {
  //     batchData.add({'name': 'Item $i'});
  //   }
  //
  //   Stopwatch stopwatch = Stopwatch()..start();
  //   await DatabaseHelper().insertBatchData(batchData);
  //   stopwatch.stop();
  //   print('数据插入成功，耗时: ${stopwatch.elapsedMilliseconds} 毫秒');
  //   // 100条数据插入成功，耗时: 103，104，120，107   47，54，46，36，39，42 毫秒
  //   // 200条数据插入成功，耗时: 135，145，137，156   70，74，67，73，80，65 毫秒
  //   // 300条数据插入成功，耗时: 160，153，155，157   95，110，97，96，97，99  毫秒
  //   // 500条数据插入成功，耗时: 230，207，238，227   154，149，141，164，154，152 毫秒
  //   // 800条数据插入成功，耗时: 314，331，305，311   229，231，236，237，229，234 毫秒
  //   // 1000条数据插入成功，耗时: 383，379，407，399   293，296，296，303，285，304 毫秒
  // }

  Future<void> insertTestData() async {
    int batchSize = 500;
    int totalRecords = 1000;
    int batches = (totalRecords / batchSize).ceil(); // 计算总共需要分几批插入数据

    Stopwatch stopwatch = Stopwatch()..start();

    for (int batchIndex = 0; batchIndex < batches; batchIndex++) {
      List<Map<String, dynamic>> batchData = [];
      int startRecord = batchIndex * batchSize;
      int endRecord = (batchIndex + 1) * batchSize;

      for (int i = startRecord; i < endRecord && i < totalRecords; i++) {
        batchData.add({'name': 'Item $i'});
      }

      await DatabaseHelper().insertBatchData(batchData);
    }

    stopwatch.stop();
    print('数据插入成功，耗时: ${stopwatch.elapsedMilliseconds} 毫秒');
    // 1000条数据插入，100一批，耗时: 476，492，572   401，397，396，395，395，404 毫秒
    // 1000条数据插入，200一批，耗时: 390，431，396   353，355，332，353，347，346 毫秒
    // 1000条数据插入，500一批，耗时: 402，382，395   308，311，300，294，283，309 毫秒
  }


  // 查询并显示测试数据
  Future<void> displayTestData() async {
    // 计算查询耗时
    Stopwatch stopwatch = Stopwatch()..start();
    List<Map<String, dynamic>>? dataList = await DatabaseHelper().getAllData();
    stopwatch.stop();
    print('查询耗时: ${stopwatch.elapsedMilliseconds} 毫秒');
    print('所有数据: $dataList');
  }


  // 删除所有数据
  Future<void> deleteAllData() async {
    await DatabaseHelper().deleteAllData();
    print('所有数据已删除');
  }
}




class MyAppfont extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => FontSizeModel(),
      child: MaterialApp(
        home: HomePage(),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var fontSizeModel = Provider.of<FontSizeModel>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Hello, World!',
              style: TextStyle(fontSize: fontSizeModel.fontSize*10),
            ),
            ElevatedButton(
              onPressed: () {
                fontSizeModel.fontSize += 0.1; //
              },
              child: Text('Increase Font Size'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => AnotherPage()),
                );
              },
              child: Text('aaaa'),
            ),
          ],
        ),
      ),
    );
  }
}






//////////////////////////////测试状态管理
class MyAppFontTest extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter widget',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePageFontTest(),
    );
  }
}

class MyHomePageFontTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Provider"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            MyContainer1(),
            SizedBox(height: 30),
            MyContainer2()
          ],
        ),
      ),
    );
  }
}

class MyContainer1 extends StatefulWidget{

  @override
  _MyContainer1State createState() => _MyContainer1State();
}

class _MyContainer1State extends State<MyContainer1> {
  @override
  Widget build(BuildContext context) {
    final String name1=Provider.of<MyCounter>(context).userInfo.name;
    final int age1=Provider.of<MyCounter>(context).userInfo.age;

    final String name2=Provider.of<MySubtract>(context).userInfo.name;
    final int age2=Provider.of<MySubtract>(context).userInfo.age;

    return Column(
      children: <Widget>[
        Text("Container1 name1=$name1  age1=$age1",style: myTextStyle1()),
        Text("Container1 name2=$name2  age2=$age2",style: myTextStyle2()),
      ],
    );
  }
}

TextStyle myTextStyle1(){
  return TextStyle(fontSize: 20,color: Colors.blue);
}

TextStyle myTextStyle2(){
  return TextStyle(fontSize: 20,color: Colors.green);
}

class MyContainer2 extends StatefulWidget{

  @override
  _MyContainer2State createState() => _MyContainer2State();
}

class _MyContainer2State extends State<MyContainer2> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Consumer2<MyCounter,MySubtract>(
        builder: (ctx,counterVM,subtractVM,child){
          return Column(
            children: <Widget>[
              Text("Container2 name1=${counterVM.userInfo.name}  age1=${counterVM.userInfo.age}",style:myTextStyle1()),
              Text("Container2 name2=${subtractVM.userInfo.name}  age2=${subtractVM.userInfo.age}",style:myTextStyle2()),
              SizedBox(height: 30,),
              EMPButton(
                text: 'aaa',
                 minHeight: 44,
                 minWidth: 200,
                onPressed: (){
                  counterVM.add();
                  subtractVM.sub();
                },
              ),
            ],
          );
        },
      ),
    );
  }
}

class UserInfo {
  String name = "leo";
  int age = 10;
  UserInfo(this.name, this.age);
}

/// with ChangeNotifier
class MyCounter with ChangeNotifier {
  UserInfo _userInfo = UserInfo("leo", 10);
  UserInfo get userInfo => _userInfo;

  void add() {
    _userInfo.age++;
    notifyListeners();
  }
}

///  extends ChangeNotifier
class MySubtract extends ChangeNotifier {
  UserInfo _userInfo = UserInfo("jim", 100);
  UserInfo get userInfo => _userInfo;

  void sub() {
    _userInfo.age--;
    notifyListeners();
  }
}

